package com.chinasoft.back.config;

import com.github.pagehelper.PageInterceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @author 中软zhang
 * @create 2023-08-24 16:18
 */
public class MybatisConfig {

    // 分页的拦截器配置
    @Bean
    public PageInterceptor getInterceptor() {
        // 创建拦截器
        PageInterceptor pageInterceptor = new PageInterceptor();
        // 设置 拦截器的数据库 方言, 数据库类型
        Properties prop = new Properties();
        prop.setProperty("helperDialect", "mysql");
        pageInterceptor.setProperties(prop);
        return pageInterceptor;
    }

    // 注入 factory 工程 bean
    @Bean
    public SqlSessionFactoryBean getFactory(DataSource ds, PageInterceptor pi) {
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setDataSource(ds);
        ssfb.setTypeAliasesPackage("com.chinasoft.back.pojo");
        // 加载配置文件
        ssfb.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        // 加载 拦截器
        ssfb.setPlugins(pi);
        return ssfb;
    }

    // 进行mapper的扫描
    @Bean
    public MapperScannerConfigurer getScaner() {
        MapperScannerConfigurer scanner = new MapperScannerConfigurer();
        scanner.setBasePackage("com.chinasoft.back.mapper");
        return scanner;
    }
}
